﻿using Microsoft.Extensions.Configuration;
using Publicuse.Entity.sqlsugar;
using Publicuse.Interface;
using Publicuse.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Service
{
    public class PostgreSQLSugarService : BaseSqlSugarService, IPostgreSQLSugarService
    {
        public PostgreSQLSugarService(ISqlSugarClient sugarClient, IConfiguration configuration) : base(sugarClient)
        {
            var mysql = new CustomConnectionConfig();
            configuration.Bind("PostgreSQLConnectionString", mysql);
            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConfigId = "PostgreSQL",
                DbType = DbType.PostgreSQL,
                IsAutoCloseConnection = true,
                MoreSettings = new ConnMoreSettings()
                {
                    PgSqlIsAutoToLower = false //数据库存在大写字段的 ，需要把这个设为false ，并且实体和字段名称要一样
                },
                ConnectionString = AesEncryptionUtil.AESDecrypt(mysql.MasterConnectionString, out var msg),
                SlaveConnectionConfigs = mysql.SlaveConnectionString.Select(c => new SlaveConnectionConfig()
                {
                    ConnectionString = AesEncryptionUtil.AESDecrypt(c.ConnectionString, out var msg),
                    HitRate = c.HitRate
                }).ToList()
            };
            //base.sugarClient= new SqlSugarClient(connectionConfig);
            base.sugarClient = new SqlSugarScope(connectionConfig);
            //调试SQL事件，可以删掉
            base.sugarClient.Aop.OnLogExecuting = (sql, pars) =>
            {
                //Console.WriteLine($"Sql语句：{sql}");
                //Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));//参数 
            };
        }
    }
}
